package com.wq.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局捕获异常类
 *
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-20 18:39
 */

//通知：告知捕获哪些类
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//以json格式返回数据
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            final String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
//            msg = msg.replace("\"", "");
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler
    public R<String> exceptionHandler(CustomerException ex) {
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
